package com.li.sssp.cp;

import java.io.Console;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.print.Doc;

import org.jsoup.Jsoup;
import org.jsoup.nodes.DataNode;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.li.sssp.cp.model.E;
import com.li.sssp.cp.model.ForecastResult;
import com.li.sssp.cp.model.Game;
import com.li.sssp.cp.model.GuestTeam;
import com.li.sssp.cp.model.HomeTeam;
import com.li.sssp.cp.model.SP;

import javafx.scene.chart.PieChart.Data;

@Controller
public class TestHandle {

	/**
	 * 常量
	 */
	private static String URL_ZC="http://www.qcw.com/buy/jczq/hh?data=&ot=2";
	private static String URL_LEAGUEH="http://info.qcw.com/league";
	private static Integer TIMEOUT=5000;
	
	/**
	 *公用变量_赛事名称
	 */
	private Integer leaguenum=0;
	
	/**
	 * 获取数据的比赛编号id列表
	 * @param doc
	 * @return
	 * @throws IOException
	 */
	public String  getZCData(Document doc) throws IOException{
		String cs_data = ""; // 需要解析的数据源

		//Document doc = Jsoup.connect(URL_ZC).get();
		Elements scripts = doc.select("script");
		for (Element script : scripts) {
			for (DataNode dataNode : script.dataNodes()) {
				String[] s = dataNode.toString().split("var");
				for (String string : s) {
					if (string.split("dgMatch").length != 1) {
						String str_data = string.substring(12);
						int num = str_data.trim().length();
						cs_data = str_data.substring(0, num - 2);
					}
				}
			}
		}
		return cs_data;
	}
	
	/**
	 * 创建game的基本信息
	 * @param base_element
	 * @return
	 */
	public Game createGame(Element base_element){

		String str_league = base_element.attr("league"); // 赛制
		String url = base_element.select("a[title=" + str_league + "]").get(0).attr("href");
		int length = url.length();
		//System.out.println(url);
		String pd_url=url;
		if("http".equals(pd_url.substring(0, 4))){
			leaguenum = Integer.parseInt(url.substring(26, length - 1));	
		}
		String str_gameInfo = base_element.attr("abbr");
		Integer int_gameId = Integer.parseInt(base_element.attr("id"));
		// beginDate
		String str_beginDate = base_element.getElementsByClass("b_time hide").first().attr("title");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		Date beginDate = null;
		try {
			beginDate = sdf.parse(str_beginDate.substring(5, str_beginDate.length()));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String str_endTime = base_element.getElementsByClass("e_time").first().attr("title");
		Date endTime = null;
		try {
			endTime = sdf.parse(str_endTime.substring(5, str_beginDate.length()));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// Date beginDate=str_beginDate.substring(5,
		// str_beginDate.length());
		Game game = new Game();
		game.setLeague(str_league);
		game.setGame_info(str_gameInfo);
		game.setGame_id(int_gameId);
		game.setBeginDate(beginDate);
		game.setEndtime(endTime);
		game.setLeagueNum(leaguenum);
		return game;
	}
	
	/**
	 * 创建SPS
	 * @param base_element
	 * @param id
	 * @return
	 */
	public List<SP> createSPS(Element base_element,String id){
		
		List<SP> sps = new ArrayList<>();
		Double sp_3 = Double
				.parseDouble(base_element.getElementById(id + "_brqspf_3").getElementsByAttribute("sp").attr("sp"));
		Double sp_1 = Double
				.parseDouble(base_element.getElementById(id + "_brqspf_1").getElementsByAttribute("sp").attr("sp"));
		Double sp_0 = Double
				.parseDouble(base_element.getElementById(id + "_brqspf_0").getElementsByAttribute("sp").attr("sp"));
		sps.add(new SP(null, sp_3, sp_1, sp_0, 0));

		Double spf_3 = Double
				.parseDouble(base_element.getElementById(id + "_spf_3").getElementsByAttribute("sp").attr("sp"));
		Double spf_1 = Double
				.parseDouble(base_element.getElementById(id + "_spf_1").getElementsByAttribute("sp").attr("sp"));
		Double spf_0 = Double
				.parseDouble(base_element.getElementById(id + "_spf_0").getElementsByAttribute("sp").attr("sp"));
		String str_concedePoints = base_element.getElementsByClass("rangqiuzhen").text();
		if (str_concedePoints.isEmpty()) {
			str_concedePoints = base_element.getElementsByClass("rangqiu").text();
		}

		int concedePoints = 0;
		if (str_concedePoints != null) {
			concedePoints = Integer.parseInt(str_concedePoints);

		}
		sps.add(new SP(null, spf_3, spf_1, spf_0, concedePoints));
		return sps;
	}
	
	/**
	 * 创建主队信息
	 * @param base_element
	 * @return
	 * @throws IOException 
	 */
	public HomeTeam createHomeTeam(Element base_element) throws IOException{
		HomeTeam homeTeam = new HomeTeam();
		Integer paim=0;
		try {
			paim= Integer.parseInt(base_element.getElementsByClass("zhu").first().select("p[class=p2]").text()
					.replace("[", "").replace("]", ""));
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		 
		String homeTeam_name = base_element.getElementsByClass("zhu").first().select("div[title]").text();
	//	System.out.println(homeTeam_name);
		homeTeam.setHomeTeam_name(homeTeam_name);
		homeTeam.setPaim(paim);
		Integer homeTeam_number=Team_num(leaguenum, homeTeam_name,paim);		
		homeTeam.setHomeTeam_number(homeTeam_number);
		homeTeam.setSixIntegrals(SixIntegrals(homeTeam_number, leaguenum));

		return homeTeam;
	}
	
	/**
	 * 创建客队信息
	 * @param base_element
	 * @return
	 * @throws IOException 
	 */
	public GuestTeam createGuestTeam(Element base_element) throws IOException{
		GuestTeam guestTeam = new GuestTeam();
		Integer paim_Guset = 0;
		try {
			paim_Guset=Integer.parseInt(base_element.getElementsByClass("fu").first().select("p[class=p2]")
					.text().replace("[", "").replace("]", ""));
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		guestTeam.setPaim(paim_Guset);
		String guestTeam_name = base_element.getElementsByClass("fu").first().select("div[title]").text();
		guestTeam.setGuestTeam_name(guestTeam_name);
		Integer team_number=(Team_num(leaguenum, guestTeam_name,paim_Guset));

		//guestTeam.setGuestTeam_num(team_number);
		guestTeam.setGuestTeam_num(team_number);
		guestTeam.setSixIntegrals(SixIntegrals(team_number, leaguenum));
	
		return guestTeam;
	}
	
	/**
	 * 最近六轮积分
	 * @return
	 * @throws IOException 
	 */
	public Integer SixIntegrals(Integer team_number,Integer league_number) throws IOException{
		Integer source = 0;
		if(team_number!=null)
		{
		String url = "http://info.qcw.com/team/" +String.valueOf(team_number)+ "/panlu";
		Document doc = Jsoup.connect(url).get();
		Element element = doc.select("tbody[class=jTrInterval his_table]").get(0);
		int count = 0;
		for (Element _a : element.select("a[href=http://info.qcw.com/league/" + league_number + "]")) {
			count += 1;
			if (count < 7) {
				String bs_data = _a.parent().parent().select("td").get(1).text(); // 比赛时间
				String key = _a.parent().parent().select("td").get(5).text();	//	比赛结果
				//System.out.println(key);
				switch (key) {
				case "胜":
					source += 3;
					break;
				case "平":
					source += 1;
				default:
					break;
				}
			}
		}
		}
		return source;
	}
	
	/**
	 * 球队编号
	 * @return
	 * @throws IOException 
	 */
	public Integer Team_num(Integer leagueNum,String teamName,Integer paim) throws IOException{
		//通过leaguenum来get数据
		Document doc = Jsoup.connect(URL_LEAGUEH + "/" + leagueNum.toString()).get();
		String teamnum = "";
		for (Element element : doc.getElementById("one_team_select").select("option")) {
			int index1 = teamName.trim().indexOf(element.text().trim());
			if (index1 != -1) {
				teamnum = element.attr("value");
			}
		}

		if (teamnum == "") {
			//System.out.println(leagueNum+"|"+teamName);
			if(doc.getElementById("hot_score_div")==null){
				return null;
			}
			Elements elements=doc.getElementById("hot_score_div").getElementById("hot_score_tbody").select("tr");
			for (Element element :elements ) {
				//System.out.println(element);
				
				if (paim == Integer.parseInt(element.select("td").get(1).text())) {
					//System.out.println(element.select("td[class=td_qiud]").get(0).select("a"));
					String _id=element.select("td[class=td_qiud]").get(0).select("a").get(0).attr("id");
					teamnum=_id.substring(4, _id.length());
				}
			}
		}
		if(teamnum==""){return null;}
		return Integer.parseInt(teamnum);
	}
	
	
	@RequestMapping(value = "Ttabpane")
	public String Ttabpane() {
		return "Ttabpane";
	}
	
	/**
	 * 根据预测结果
	 * @param game
	 * @return
	 */
	public ForecastResult Calculate(Game game) {
		if (isCheck(game.getSps().get(0))) {
			
			ForecastResult forecastResult = new ForecastResult();
//			Integer homePaim = game.getHomeTeam().getPaim();
//			Integer guestPaim = game.getGuestTeam().getPaim();
			
			double ze = game.getEs().get(0).getResult();
			double pe = game.getEs().get(1).getResult();
			double ke = game.getEs().get(2).getResult();
			
			if (ze > 0.96 && ze < pe && ze < ke && (Math.abs(ze - ke) > 0.08)) {	//	主胜
				forecastResult.seteResult(ze);
				forecastResult.setSp(game.getSps().get(0).getSp_3().toString());
				forecastResult.setGuess("3");
			}else if(ke<0.96){	//	客不胜
				forecastResult.seteResult(ke);
				forecastResult.setSp(game.getSps().get(0).getSp_0().toString()+","+game.getSps().get(0).getSp_1().toString());
				forecastResult.setGuess("3,1");
			}else if((ke>0.96 && ke<ze && ke<pe && (Math.abs(ze-pe)>0.03))||(ze<0.90)){ //主不胜
				forecastResult.seteResult(ke);
				forecastResult.setSp(game.getSps().get(0).getSp_0().toString()+","+game.getSps().get(0).getSp_0().toString());
				forecastResult.setGuess("1,0");
			}else if(ke>0.96 && ke<ze && (Math.abs(ze-ke)>0.08)){	//	客胜
				forecastResult.seteResult(ke);
				forecastResult.setSp(game.getSps().get(0).getSp_0().toString());
				forecastResult.setGuess("0");
			}else{
				return null;
			}
		return forecastResult;
		}
		return null;
	}
	
	/**
	 * 是否符合预测条件
	 * @param sp
	 * @return
	 */
	public Boolean isCheck(SP sp){
		double threshold=2.0;
		if(sp.getSp_0()>threshold&&sp.getSp_1()>threshold&&sp.getSp_3()>threshold){
			return true;
		}
		return false;
	}
 	
	/**
	 * elo预测法计算E值
	 * @param game
	 * @return
	 */
	public List<E> getE(Game game){
		
		Integer homePaim = game.getHomeTeam().getPaim();
		Integer guestPaim = game.getGuestTeam().getPaim();
		Double zsp = game.getSps().get(0).getSp_3();
		double psp=game.getSps().get(0).getSp_1();
		double ksp=game.getSps().get(0).getSp_0();
		List<E> es=new ArrayList<>();
		double zResult= (0.45 - 0.0053 * (homePaim - guestPaim)) * zsp;
		double pResult=(0.45 - 0.0053 * (homePaim - guestPaim)) * psp;
		double kResult=(0.45 - 0.0053 * (guestPaim-homePaim)) * ksp;
		E ze=new E(null,zResult,"ze");
		E pe=new E(null,pResult,"pe");
		E ke=new E(null,kResult,"ke");
		
		es.add(ze);
		es.add(pe);
		es.add(ke);
		return es;
	}
	
	
//	public void test_Game() throws IOException{
//		System.out.println("开始");
//		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//可以方便地修改日期格式
//		SimpleDateFormat dateRangeFormat = new SimpleDateFormat("yyMMdd");
//		Integer int_range=(Integer.valueOf((dateRangeFormat.format(new Date()).toString()))+1)*1000;
//		//System.out.println(int_range);
//		
//		Document doc = Jsoup.connect(URL_ZC)
//				.userAgent("Mozilla/5.0 (Windows NT 6.1; rv:23.0) Gecko/20100101 Firefox/23.0")
//				.ignoreContentType(true)
//				.timeout(TIMEOUT)
//				.maxBodySize(0)
//				.get();		//	获取源
//			String cs_data = getZCData(doc); // 获取比赛数据
//			
//		List<Game> games = new ArrayList<>(); // 创建game集合
//
//		for (String item : cs_data.split(",")) { // 填充内容
////			System.out.println(dateFormat.format(new Date()));
//			String id = item.replace("\"", "");
//			if (Integer.parseInt(id) < int_range) {
//				Element base_element = doc.getElementById(id);
//				Game game = createGame(base_element); // 创建game
//				game.setHomeTeam(createHomeTeam(base_element)); // 创建主队信息
//				System.out.println("创建HomeTeam：" + game.sixIntegrals().toString()+dateFormat.format(new Date()));
////				game.setGuestTeam(createGuestTeam(base_element)); // 创建客队信息
////				System.out.println("创建GuestTeam：" + dateFormat.format(new Date()));
////				game.setSps(createSPS(base_element, id)); // 增加sps
////				System.out.println("创建SPS：" + dateFormat.format(new Date()));
////				game.setEs(getE(game)); // 计算各种E的结果
////				System.out.println("创建Es：" + dateFormat.format(new Date()));
////				game.setForecastResult(Calculate(game)); // 预测结果
////				System.out.println("创建Result：" + dateFormat.format(new Date()));
////				games.add(game);
//			}
//
//		}
////		
////		ObjectMapper mapper = new ObjectMapper();
////		try {
////			return mapper.writeValueAsString(games);	//	输出json
////
////		} catch (JsonGenerationException e) {
////		}
//		//return "hello";
//	}
	
	/**
	 * 组装game数据生成Json格式
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("cp/getGame")
	@ResponseBody
	public String Game() throws IOException{
		System.out.println("开始");
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//可以方便地修改日期格式
		SimpleDateFormat dateRangeFormat = new SimpleDateFormat("yyMMdd");
		Integer int_range=(Integer.valueOf((dateRangeFormat.format(new Date()).toString()))+1)*1000;
		//System.out.println(int_range);
		
		Document doc = Jsoup.connect(URL_ZC)
				.userAgent("Mozilla/5.0 (Windows NT 6.1; rv:23.0) Gecko/20100101 Firefox/23.0")
				.ignoreContentType(true)
				.timeout(TIMEOUT)
				.maxBodySize(0)
				.get();		//	获取源
		//System.out.println(doc);
		String cs_data = getZCData(doc); // 获取比赛数据
		List<Game> games = new ArrayList<>(); // 创建game集合

		for (String item : cs_data.split(",")) { // 填充内容
			System.out.println(dateFormat.format(new Date()));

			String id = item.replace("\"", "");
			if (Integer.parseInt(id) < int_range) {

				Element base_element = doc.getElementById(id);

				Game game = createGame(base_element); // 创建game

				System.out.println("创建Game：" + dateFormat.format(new Date()));
				game.setHomeTeam(createHomeTeam(base_element)); // 创建主队信息
				System.out.println("创建HomeTeam：" + dateFormat.format(new Date()));
				game.setGuestTeam(createGuestTeam(base_element)); // 创建客队信息
				System.out.println("创建GuestTeam：" + dateFormat.format(new Date()));
				game.setSps(createSPS(base_element, id)); // 增加sps
				System.out.println("创建SPS：" + dateFormat.format(new Date()));
				game.setEs(getE(game)); // 计算各种E的结果
				System.out.println("创建Es：" + dateFormat.format(new Date()));
				game.setForecastResult(Calculate(game)); // 预测结果
				System.out.println("创建Result：" + dateFormat.format(new Date()));
				games.add(game);
			}

		}
		
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.writeValueAsString(games);	//	输出json

		} catch (JsonGenerationException e) {
		}
		return "hello";
	}
	
	
	@RequestMapping(value = "cp/index")
	public String Index(Map<String, Object> map) throws IOException {
	//System.out.println(SixIntegrals(2280,261)); 
		
		
		return "cp/index";
	}
}
